<?php
namespace App\Admin\Controllers\Products;

use App\Importer\Products\MixSku\SkuImporter;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductMixSku;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use App\Util\SerialSkuNo;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class MixSkuUploadController extends AdminController{

    protected $title = '组合产品上传';

    protected function grid()
    {
        $type = request('type');
        return view("products.mix-sku.upload.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importSku(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $userId = Admin::user()->id;
            $pSkuCnArr = [];
            foreach($data as $row){
                $count++;
                $pSkuCn = $row[0] ? trim($row[0]) : '';
                $classify = $row[1] ? trim($row[1]) : '';
                $pSkuStatus = $row[2] ? trim($row[2]) : '';
                $mixRule = $row[3] ? trim($row[3]) : '';
                $pSkuDescribe = $row[4] ? trim($row[4]) : '';

                if(!$pSkuCn || !$classify || !$pSkuStatus || !$mixRule){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                if(!in_array($pSkuCn,$pSkuCnArr)){
                    $pSkuCnArr[$count] = $pSkuCn;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $reCount = ProductSku::query()->where('psku_cn',$pSkuCn)->count();
                if($reCount > 0){
                    $errors[$count] = $pSkuCn.'系统已存在';
                    continue;
                }
                $classifyId = ProductClassify::getIdByTitle($classify);
                if(!$classifyId){
                    $errors[$count] = '品类不存在';
                    continue;
                }
                if(!in_array($pSkuStatus,ProductSku::$_pSkuStatus)){
                    $errors[$count] = $pSkuStatus.'产品状态不存在，请选择'.implode('、',ProductSku::$_pSkuStatus);
                    continue;
                }
                $flag = ProductMixSku::checkMixRule($mixRule);
                if(!$flag){
                    $errors[$count] = '关联产品必须为普通产品';
                    continue;
                }

                $pSkuCode = SerialSkuNo::init();
                $partNumber = str_replace('AM','PN',$pSkuCode);
                $codeCount = ProductSku::query()->where('psku_code',$pSkuCode)->count();
                if($codeCount > 0){
                    $errors[$count] = $pSkuCode.'(sku编码)系统已存在';
                    continue;
                }

                DB::beginTransaction();
                $arr = ProductMixSku::getMpSku($mixRule);
                $ps = ProductMixSku::query()->create(
                    [
                        'psku_code' => $pSkuCode,
                        'part_number' => $partNumber,
                        'psku_cn' => $pSkuCn,
                        'classify_id' => $classifyId,
                        'psku_status' => array_search($pSkuStatus,ProductSku::$_pSkuStatus),
                        'psku_describe' => $pSkuDescribe ? str_replace('@',PHP_EOL,$pSkuDescribe) : null,
                        'is_mix' => 1,
                        'mix_rule' => $mixRule,
                        'm_psku_id' => $arr['m_psku_id'],
                        'm_num' => $arr['m_num'],
                        'muser_id' => $userId,
                        'cuser_id' => $userId,
                        'is_brand' => ProductSku::BRAND_NO, //非品牌产品
                    ]
                );
                if($ps){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    private function _importSkuUp(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $skuArr = [];
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $pSkuCn = $row[1] ? trim($row[1]) : '';
                $classify = $row[2] ? trim($row[2]) : '';
                $pSkuStatus = $row[3] ? trim($row[3]) : '';
                $pSkuDescribe = $row[4] ? trim($row[4]) : '';
                $mUser = $row[5] ? trim($row[5]) : '';
                $status = $row[6] ? trim($row[6]) : '';
                if(!$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                if(!in_array($sku,$skuArr)){
                    $skuArr[$count] = $sku;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                DB::beginTransaction();
                $ps = ProductMixSku::query()->where('psku_code',$sku)->first();
                if(!$ps){
                    $errors[$count] = $sku.'系统不存在';
                    DB::rollBack();
                    continue;
                }
                if($pSkuCn){
                    $ps->psku_cn = $pSkuCn;
                }
                if($classify){
                    $classifyId = ProductClassify::getIdByTitle($classify);
                    if(!$classifyId){
                        $errors[$count] = '品类不存在或已停用';
                        DB::rollBack();
                        continue;
                    }
                    $ps->classify_id = $classifyId;
                }
                if($pSkuStatus){
                    if(!in_array($pSkuStatus,ProductSku::$_pSkuStatus)){
                        $errors[$count] = $pSkuStatus.'产品状态不存在，请选择'.implode('、',ProductSku::$_pSkuStatus);
                        DB::rollBack();
                        continue;
                    }
                    $ps->psku_status = array_search($pSkuStatus,ProductSku::$_pSkuStatus);
                }
                if($pSkuDescribe){
                    $ps->psku_describe = str_replace('@',PHP_EOL,$pSkuDescribe);
                }
                if($mUser){
                    $userId = User::getIdByUsername($mUser);
                    if(!$userId){
                        $errors[$count] = $mUser.'产品负责人不存在或已停用';
                        DB::rollBack();
                        continue;
                    }
                    $ps->muser_id = $userId;
                }
                if($status){
                    if(!in_array($status,ProductSku::$_status)){
                        $errors[$count] = $status.'不存在，请选择'.implode('、',ProductSku::$_status);
                        continue;
                    }
                    $ps->status = array_search($status,ProductSku::$_status);
                }
                $flag = $ps->save();
                if($flag){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    /**
     * 上传品牌产品
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importSkuBrand(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $userId = Admin::user()->id;
            $pSkuCnArr = [];
            foreach($data as $row){
                $count++;
                $pSkuCn = $row[0] ? trim($row[0]) : '';
                $classify = $row[1] ? trim($row[1]) : '';
                $pSkuStatus = $row[2] ? trim($row[2]) : '';
                $mixRule = $row[3] ? trim($row[3]) : '';
                $pSkuDescribe = $row[4] ? trim($row[4]) : '';

                $_classifyCode = $row[5] ? trim($row[5]) : '';
                $_itemNumber = $row[6] ? trim($row[6]) : '';
                $_yearNumber = $row[7] ? trim($row[7]) : '';
                $_seasonCode = $row[8] ? trim($row[8]) : '';
                $_colorCode = $row[9] ? trim($row[9]) : '';
                $_specCode = $row[10] ? trim($row[10]) : '';

                $classifyCode = strtoupper($_classifyCode);
                $itemNumber = $_itemNumber;
                $yearNumber = $_yearNumber;
                $seasonCode = strtoupper($_seasonCode);
                $colorCode = strtoupper($_colorCode);
                $specCode = strtoupper($_specCode);

                if(!$pSkuCn || !$classify || !$pSkuStatus || !$mixRule){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                if (!$classifyCode || !$itemNumber || !$yearNumber || !$seasonCode || !$colorCode || !$specCode) {
                    $errors[$count] = 'sku必填项为空';
                    continue;
                }
                if (!preg_match("/^[A-Z]{3}$/", $classifyCode)) {
                    $errors[$count] = '品类名不正确/不存在';
                    continue;
                }
                if (!preg_match("/^[0-9]{2}$/", $itemNumber)) {
                    $errors[$count] = '款号不正确/不存在';
                    continue;
                }
                if (!preg_match("/^[0-9]{2}$/", $yearNumber)) {
                    $errors[$count] = '年份不正确/不存在';
                    continue;
                }
                if (!preg_match("/^[A-Z]{2}$/", $seasonCode)) {
                    $errors[$count] = '季节不正确/不存在';
                    continue;
                }
                if (!preg_match("/^[A-Z]{2}$/", $colorCode)) {
                    $errors[$count] = '颜色不正确/不存在';
                    continue;
                }
                if (!preg_match("/^[A-Z0-9]{2}$/", $specCode)) {
                    $errors[$count] = '规格不正确/不存在';
                    continue;
                }

                if(!in_array($pSkuCn,$pSkuCnArr)){
                    $pSkuCnArr[$count] = $pSkuCn;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $reCount = ProductSku::query()->where('psku_cn',$pSkuCn)->count();
                if($reCount > 0){
                    $errors[$count] = $pSkuCn.'系统已存在';
                    continue;
                }
                $classifyId = ProductClassify::getIdByTitle($classify);
                if(!$classifyId){
                    $errors[$count] = '品类不存在';
                    continue;
                }
                if(!in_array($pSkuStatus,ProductSku::$_pSkuStatus)){
                    $errors[$count] = $pSkuStatus.'产品状态不存在，请选择'.implode('、',ProductSku::$_pSkuStatus);
                    continue;
                }
                $flag = ProductMixSku::checkMixRule($mixRule);
                if(!$flag){
                    $errors[$count] = '关联产品必须为普通产品';
                    continue;
                }

                $pSkuCode = $classifyCode.$itemNumber.$yearNumber.$seasonCode.$colorCode.$specCode;
                $partNumber = $pSkuCode;
                $codeCount = ProductSku::query()->where('psku_code',$pSkuCode)->count();
                if($codeCount > 0){
                    $errors[$count] = $pSkuCode.'(sku编码)系统已存在';
                    continue;
                }

                DB::beginTransaction();
                $arr = ProductMixSku::getMpSku($mixRule);
                $ps = ProductMixSku::query()->create(
                    [
                        'psku_code' => $pSkuCode,
                        'part_number' => $partNumber,
                        'psku_cn' => $pSkuCn,
                        'classify_id' => $classifyId,
                        'psku_status' => array_search($pSkuStatus,ProductSku::$_pSkuStatus),
                        'psku_describe' => $pSkuDescribe ? str_replace('@',PHP_EOL,$pSkuDescribe) : null,
                        'is_mix' => 1,
                        'mix_rule' => $mixRule,
                        'm_psku_id' => $arr['m_psku_id'],
                        'm_num' => $arr['m_num'],
                        'muser_id' => $userId,
                        'cuser_id' => $userId,

                        'classify_code' => $classifyCode,
                        'item_number' => $itemNumber,
                        'year_number' => $yearNumber,
                        'season_code' => $seasonCode,
                        'color_code' => $colorCode,
                        'spec_code' => $specCode,
                        'is_brand' => ProductSku::BRAND_YES, //品牌产品
                    ]
                );
                if($ps){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    /**
     * 更新品牌产品
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importSkuUpBrand(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $skuArr = [];
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $pSkuCn = $row[1] ? trim($row[1]) : '';
                $classify = $row[2] ? trim($row[2]) : '';
                $pSkuStatus = $row[3] ? trim($row[3]) : '';
                $pSkuDescribe = $row[4] ? trim($row[4]) : '';
                $mUser = $row[5] ? trim($row[5]) : '';
                $status = $row[6] ? trim($row[6]) : '';
                if(!$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                if(!in_array($sku,$skuArr)){
                    $skuArr[$count] = $sku;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                DB::beginTransaction();
                $ps = ProductMixSku::query()->where('psku_code',$sku)->first();
                if(!$ps){
                    $errors[$count] = $sku.'系统不存在';
                    DB::rollBack();
                    continue;
                }
                if($pSkuCn){
                    $ps->psku_cn = $pSkuCn;
                }
                if($classify){
                    $classifyId = ProductClassify::getIdByTitle($classify);
                    if(!$classifyId){
                        $errors[$count] = '品类不存在或已停用';
                        DB::rollBack();
                        continue;
                    }
                    $ps->classify_id = $classifyId;
                }
                if($pSkuStatus){
                    if(!in_array($pSkuStatus,ProductSku::$_pSkuStatus)){
                        $errors[$count] = $pSkuStatus.'产品状态不存在，请选择'.implode('、',ProductSku::$_pSkuStatus);
                        DB::rollBack();
                        continue;
                    }
                    $ps->psku_status = array_search($pSkuStatus,ProductSku::$_pSkuStatus);
                }
                if($pSkuDescribe){
                    $ps->psku_describe = str_replace('@',PHP_EOL,$pSkuDescribe);
                }
                if($mUser){
                    $userId = User::getIdByUsername($mUser);
                    if(!$userId){
                        $errors[$count] = $mUser.'产品负责人不存在或已停用';
                        DB::rollBack();
                        continue;
                    }
                    $ps->muser_id = $userId;
                }
                if($status){
                    if(!in_array($status,ProductSku::$_status)){
                        $errors[$count] = $status.'不存在，请选择'.implode('、',ProductSku::$_status);
                        continue;
                    }
                    $ps->status = array_search($status,ProductSku::$_status);
                }
                $flag = $ps->save();
                if($flag){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
